package com.xzg.mission.Service;

import com.xzg.common.constants.Constant;
import com.xzg.common.exception.XZGException;
import com.xzg.common.page.PageQueryBean;
import com.xzg.common.push.PushtoAPP;
import com.xzg.common.resp.APIResult;
import com.xzg.common.utils.DateUtil;
import com.xzg.common.vo.QueryCondition;
import com.xzg.middleTable.dao.*;
import com.xzg.middleTable.entity.*;
import com.xzg.mission.dao.MissionMapper;
import com.xzg.mission.entity.Mission;
import com.xzg.user.dao.UserMapper;
import com.xzg.user.entity.User;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.plugin.services.WIExplorerBrowserService;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MissionServiceImpl implements MissionService {

    @Autowired
    private MissionMapper missionMapper;

    @Autowired
    private UserMissionMapper userMissionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private MissionCategoryMapper missionCategoryMapper;

    @Autowired
    private TmissionMapper tmissionMapper;

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private LabelTMissionMapper labelTMissionMapper;
    /**
     * @Author Ye
     * Date 2018-03-05 16:19
     * @Description 查询所有任务并分页
     */
    @Override
    public PageQueryBean listMission(QueryCondition condition) {
        //记录数目
        int count = missionMapper.countByCondition(condition);
        PageQueryBean pageResult = new PageQueryBean();
        if (count > 0) {
            pageResult.setTotalRows(count);
            pageResult.setCurrentPage(condition.getCurrentPage());
            pageResult.setPageSize(condition.getPageSize());
            List<Mission> missionList = missionMapper.allMission(condition);
            pageResult.setItems(missionList);
        }


        return pageResult;
    }

    @Override
    public int createMission(Mission mission) {
        int count = missionMapper.insertSelective(mission);
        if (count > 0) {
            try {
                PushtoAPP.toAPP();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 1;
        }
        return 0;
    }

    @Override
    public PageQueryBean missionPart(QueryCondition condition) throws ParseException {
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        condition.setLabelList(user.getListLabel());
        Calendar cl = Calendar.getInstance();
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String str = condition.getStartDate();
        Date date1 = format1.parse(str);
        cl.setTime(date1);
        java.util.Date date = DateUtil.getBeforeDay(cl).getTime();
        condition.setMissionDate(date);
        //记录数目
        int count = missionMapper.countByCondition(condition);
        PageQueryBean pageResult = new PageQueryBean();
        if (count > 0) {
            pageResult.setTotalRows(count);
            pageResult.setCurrentPage(condition.getCurrentPage());
            pageResult.setPageSize(condition.getPageSize());
            List<Mission> missionList = missionMapper.partMission(condition);
            pageResult.setItems(missionList);
        }
        return pageResult;
    }

    /**
     * @Author Ye
     * Date 2018-03-07 16:56
     * @Description 删除任务
     */
    @Override
    public void deleteMission(Long id) {
        missionMapper.deleteByPrimaryKey(id);
    }

    /**
     * @Author Ye
     * Date 2018-03-07 16:56
     * @Description
     */
    @Override
    public Mission findOne(Long id) throws XZGException {

        Mission mission = missionMapper.selectByPrimaryKey(id);
        List<Long> userIds = userMissionMapper.selectByMissionId(mission.getMissionId());
        HashMap<String, Object> userIdParam = new HashMap<>();
        userIdParam.put("userIds", userIds);
        if (userIds.size() > 0) {
            List<User> listuser = userMapper.queryNameByIds(userIdParam);
            mission.setListUsername(listuser);
        }
        return mission;

    }

    @Override
    @Transactional
    public APIResult inserCategory(Category category) {
        APIResult resp = new APIResult();
        try {
            if (category.getCategoryName() != null && category.getCategoryName() != "") {
                categoryMapper.insertSelective(category);
                resp.setMessage("添加成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("添加失败");
            resp.setCode(Constant.RESP_STATUS_INTERNAL_ERROR);
        }
        return resp;
    }

    /**
     * @Author: ye
     * @Date: 16:06 2018\4\10 0010
     * @Description 先绑定第一个大的分类 category
     * 再绑定一个小的标签template template需要先判断是否为空当不空为空的时候执行绑定
     */
    @Override
    @Transactional
    public APIResult categoryMission(Tmission mission) {
        APIResult resp = new APIResult();
        try {
            //任务绑定第一个分类
            MissionCategory missionCategory = new MissionCategory();
            missionCategory.setCategoryId(mission.getCategoryId());
            tmissionMapper.insertSelective(mission);
            missionCategory.setcMissionId(mission.gettMissionId());
            //插入任务和分类中间表
            missionCategoryMapper.insertSelective(missionCategory);
            //判断小标签是否为空
            if (!mission.getLabelList().isEmpty()) {
                //给任务绑定小标签，拿到当前任务的id或者名字 插入中间表
                List<LabelTMission> list = new ArrayList();
                for (Long lid : mission.getLabelList()) {
                    LabelTMission labelTMission = new LabelTMission();
                    labelTMission.setLtLabelId(lid);
                    labelTMission.setLtTmissionId(mission.gettMissionId());
                    list.add(labelTMission);
                }
                labelTMissionMapper.batchInsert(list);
            }
            PushtoAPP.toAPP();
            resp.setMessage("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("添加失败");
            resp.setCode(Constant.RESP_STATUS_INTERNAL_ERROR);
        }
        return resp;
    }

    /**
     * @Author: ye
     * @Date: 16:50 2018\4\10 0010
     * @Description 查询所有分类
     */
    @Override
    public APIResult categoryAll() {
        APIResult resp = new APIResult();
        try {
            List<Category> category = categoryMapper.selectAll();
            resp.setData(category);
            resp.setMessage("查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("查询失败");
        }
        return resp;
    }

    /**
     * @Author: ye
     * @Date: 16:49 2018\4\10 0010
     * @Description 删除分类标签
     */
    @Override
    public APIResult deleteCategory(Long categoryCid) {
        APIResult resp = new APIResult();
        try {
            categoryMapper.deleteByPrimaryKey(categoryCid);
            resp.setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("删除失败");
            resp.setCode(Constant.RESP_STATUS_INTERNAL_ERROR);
        }
        return resp;
    }

    /**
     * @Author: ye
     * @Date: 10:09 2018\4\11 0011
     * @Description 查询当前分类下的所有任务
     */
    @Override
    public PageQueryBean findTMission(QueryCondition condition) {
        PageQueryBean pageResult = new PageQueryBean();
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        condition.setLabelList(user.getListLabel());
        try {
            int count = tmissionMapper.countMission();
            if (count > 0) {
                pageResult.setTotalRows(count);
                pageResult.setCurrentPage(condition.getCurrentPage());
                pageResult.setPageSize(condition.getPageSize());
                List<Tmission> list = tmissionMapper.selectTMission(condition);
                pageResult.setItems(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }

    @Override
    public APIResult updateTMission(Tmission tmission) {
        APIResult resp = new APIResult();
        try{
            tmissionMapper.updateByPrimaryKeySelective(tmission);
            resp.setMessage("修改成功");
        }catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("编辑失败");
            resp.setCode(Constant.RESP_STATUS_INTERNAL_ERROR);
        }
        return resp;
    }

    @Override
    public APIResult deleteTMission(Tmission tmission) {
        APIResult resp = new APIResult();
        try {
            tmissionMapper.deleteByPrimaryKey(tmission.gettMissionId());
            resp.setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("删除失败");
            resp.setCode(Constant.RESP_STATUS_INTERNAL_ERROR);
        }
        return resp;
    }


}
